package com.xof.phonecall.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager

class PhoneCallBroadcastReceiver : BroadcastReceiver() {

    private lateinit var mMyPhoneStateListener: MyPhoneStateListener
    private var mOnActionListener: (PhoneCallState) -> Unit = { item -> }

    override fun onReceive(context: Context?, intent: Intent?) {
        context?.let { ctx ->
            val telephonyManager: TelephonyManager =
                ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager

            mMyPhoneStateListener = MyPhoneStateListener()
            mMyPhoneStateListener.setActionListener { phoneCallState ->
                mOnActionListener.invoke(phoneCallState)
            }
            telephonyManager.listen(mMyPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE)
        }
    }

    fun setActionListener(listener: (PhoneCallState) -> Unit) {
        mOnActionListener = listener
    }
}